var mongoose = require('mongoose');
var News = require('../model/news.model');

const Cate=require('../model/cate.model');

exports.get=function (req,res,next){
    const id=req.params.id;
    News.findById(id,function(err,data){
        res.json(data);
    })
}

/* 增 */
exports.create = function(req,res,next){
    const news = new News(req.body); // 请示方式是post
    news.save()
    .then(data=>{
        res.json(data);
        // console.log(res.json(data));
    })
}

/* 修 */
// 参数：设参 传参 接参
exports.update = function(req,res,next){
    // 两种不同的参数传递方式
    const id = req.params.id;
    const news = new News(req.body);

    News.findByIdAndUpdate(id, { $set: req.body }, {new: false})
    .then(data=>{
        res.json(data); // 千万注意：这里返回的data是没有修改之前的数据
    })

}

/* 删 */
exports.remove = function(req,res,next){
    const id = req.params.id;
    News.findByIdAndRemove(id,function(err,data){
        res.json({'message':'数据已删除'})
    })    
}

/* 删多个 */

exports.removes = function(req,res,next){
    var ids = req.body.ids;
    // console.log(ids);
    ids=ids.split(',');
    
    if(ids.length>0){
        News.remove( { _id: {$in: ids }})
        .then(data=>{
            res.json({'message':'多条数据已删除'});
        })
    }else{
        res.status(404).send({'message':'404'});
    }
}

exports.list=function(req,res,next){
    var page=(req.body.page) ? req.body.page:1;
    var rows = (req.body.rows) ? req.body.rows : 10;

    var queryCondition = {};

    if(req.body.title && req.body.title.trim().length>0){
        title = req.body.title;
        queryCondition = {
            "title": new RegExp(title,'i')
        }
    }

    if(req.body.cateId && req.body.cateId.trim().length>0){
        id = req.body.cateId;
        var ids=[];
        Cate.findOne({_id:id},function(err,doc){
            if(doc){
                ids.push(doc.id);//加入该项
                doc.getChildren().then(function(docs){
                    for(var i=0;i<docs.length;i++){
                        ids.push(docs[i]._id);
                    } 
                    queryCondition = Object.assign(queryCondition,{           
                        cateId: {$in : ids}
                    })
                    //console.log('22',queryCondition)
                    News.paginate(queryCondition,{ page: +page, limit: +rows},function (err,result){
                       // console.log('222',queryCondition,rows);
                        result.rows = result.docs;
                        delete result.docs;
                        res.json(result);
                    })
                })               
            }        
        })       
    }else{
        News.paginate(queryCondition,{ page: +page, limit: +rows},function (err,result){
            result.rows = result.docs;
            delete result.docs;
            res.json(result);
        })
    }

}